<!-- 预览时触发 -->
<template>
    <!--     <h3>{{data.config.formName}}</h3> -->


    <div>

        <el-form ref="generateForm"
                 :class="{
        [data.config.customClass]: data.config.customClass?true: false}"
                 label-suffix=":"
                 :size="data.config.size"
                 :model="models" :label-position="data.config.labelPosition"
                 :label-width="data.config.labelWidth + 'px'">
            <!-- 循环数据,调用生成具体表单的方 -->
            <template v-for="item in data.list">
                <generate-col-item
                        v-if="item.type == 'grid' || item.type == 'subTable' &&item.options.show == true "
                        :key="item.key"
                        :model.sync="models"
                        :element="item"
                        :remote="remote"
                        :blanks="blanks"
                        :models_temp="models_temp"
                        :strutAll="data"
                >

                    <template v-slot:[blank.name]="scope" v-for="blank in blanks">
                        <slot :name="blank.name" :model="scope.model"></slot>

                    </template>
                </generate-col-item>

                <span v-else-if="item.type == 'block' && item.options.show==true">
         <generate-form-item
                 :key="item.key"
                 :models.sync="models"
                 :widget="item"
                 :taskId="taskId"
                 :remote="remote"
                 :blanks="blanks"
                 :models_temp="models_temp"
                 :strutAll="data"
         >
          <el-row></el-row>
          <template v-slot:[blank.name]="scope" v-for="blank in blanks">
            <slot :name="blank.name" :model="scope.model"></slot>
          </template>
        </generate-form-item>
      </span>
                <span v-else-if="item.type == 'card' && item.options.show==true">
         <generate-form-item
                 :key="item.key"
                 :models.sync="models"
                 :widget="item"
                 :taskId="taskId"
                 :remote="remote"
                 :blanks="blanks"
                 :models_temp="models_temp"
                 :strutAll="data"
         >
          <el-row></el-row>
          <template v-slot:[blank.name]="scope" v-for="blank in blanks">
            <slot :name="blank.name" :model="scope.model"></slot>
          </template>
        </generate-form-item>
      </span>
                <span v-else-if="item.type == 'tabs' && item.options.show==true">

         <generate-form-item
                 :key="item.key"
                 :models.sync="models"
                 :widget="item"
                 :taskId="taskId"
                 :remote="remote"
                 :blanks="blanks"
                 :models_temp="models_temp"
                 :strutAll="data"
         >
          <el-row></el-row>
          <template v-slot:[blank.name]="scope" v-for="blank in blanks">
            <slot :name="blank.name" :model="scope.model"></slot>
          </template>
        </generate-form-item>
      </span>
                <span v-else>
        <generate-form-item
                v-if="item.options.show == true "
                :key="item.key"
                :models.sync="models"
                :widget="item"
                :taskId="taskId"
                :remote="remote"
                :blanks="blanks"
                :models_temp="models_temp"
                :strutAll="data"
        >
          <el-row></el-row>
          <template v-slot:[blank.name]="scope" v-for="blank in blanks">
            <slot :name="blank.name" :model="scope.model"></slot>
          </template>
        </generate-form-item>
              </span>
            </template>
        </el-form>
    </div>


</template>

<script>
    import GenerateFormItem from './GenerateFormItem'
    import GenerateColItem from './GenerateColItem'
    import {filterModel} from  './router/utils.js'
    import request from '../util/request.js'
    import qs from 'qs'
    import  vm from '../main'
    export default {
        name: 'fm-generate-form',
        components: {
            GenerateFormItem,
            GenerateColItem
        },
        props: ['data', 'remote', 'value', 'insite','builtMap','taskId'],
        data() {
            return {
                models_temp: [],
                models: {},
                rules: {},
                blanks: [],
                values: [],
                dynamicMethodEvent:{}

            }
        },
        created() {
            var customStyle = this.data.config.customStyle;
            var customJs = this.data.config.customJs;
            if (customStyle) {
                let style = document.createElement('style');
                style.type = "text/css";
                style.innerText = customStyle;
                document.getElementsByTagName('head')[0].appendChild(style)
            }
            if (customJs) {
                var cjs = customJs.split(';')
                for (let i = 0; i < cjs.length; i++) {
                    var cj = cjs[i];
                    this.createScript(cj);
                }
            }


            // //this.buildRules(this.data.list);
            // console.log(this.models);
            // console.log(this.rules);
            if (this.value && !(JSON.stringify(this.value) == "{}")) {
                this.models = this.value;
            } else {
                this.generateModel(this.data.list);
            }
            this.$nextTick(() => {
                var jsExpand=  this.data.config.jsExpand;

                var scriptContext=jsExpand;
                // 创建script标签，执行script内容
                let script = document.createElement('script')
                script.type = 'text/javascript'
                script.text = scriptContext
                document.getElementsByTagName('head')[0].appendChild(script)
             //
             // alert(jsExpand)
            })
        },
        mounted() {
            window.api = this;

        },
        methods: {
            pushRule:function(model,rules){
                //获取所有的控件
               var list= this.data.list;
               if (list){
                   //查找当前的节点，如果存在就添加规则
                var node=    filterModel(list,model);
                if (node){
                    node[0].rules.push(rules)
                }
               }
            },
            watch:function(obj){
            this.dynamicMethodEvent=obj
            },
            async get(url, parameter) {
                let get = ()=>{
                   var data=  qs.stringify(parameter)
                    return new Promise(resolve => {

                         request({
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            url: url+"/?"+data,
                            method: 'GET',
                        }).then(res => {
                             result=res
                             resolve(res);
                         })

                    });
                }
                let result = await get();
                return result;

            },
            async post(url, parameter) {
                let post = ()=>{
                   var data=  qs.stringify(parameter)
                    return new Promise(resolve => {

                         request({
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            url: url,
                            method: 'POST',
                             data: JSON.stringify(data)
                        }).then(res => {
                             result=res
                             resolve(res);
                         })

                    });
                }
                let result = await post();
                return result;

            },
            validate:function(){
                this.$refs.generateForm.validate(valid => {
                    return valid;
                });
            },
            resetFields:function(){
                this.$refs.generateForm.resetFields()
            },
            getFormData:function(key){
                if (key){
                    return this.models[key]
                } else{
                    return this.models
                }

            },
            setFormData:function(key, value){
                this.models[key]=value
            },
            show:function(key){
             if (key){
                 var result=key.split(",");
                 var list=   this.data.list;
                 for (var i = 0; i <result.length ; i++) {
                     var node=  filterModel(list,result[i])
                     if (node && node.length>0){
                         node[0].options.show=true;
                     }
                 }
             } else{

             }
            },
            hide:function(key){

             if (key){
                 var result=key.split(",");
                 var list=   this.data.list;
                 for (var i = 0; i <result.length ; i++) {
                     var node=  filterModel(list,result[i])
                     if (node && node.length>0){
                         node[0].options.show=false;
                     }
                 }
             } else{

             }
            },

            createScript: function (js) {
                let script = document.createElement('script')
                script.type = 'text/javascript'
                script.src = js
                document.getElementsByTagName('head')[0].appendChild(script)
            },
            generateModel(genList) {
                for (let i = 0; i < genList.length; i++) {
                    if (genList[i].type == 'block') {
                        this.models[genList[i].model] = [];
                        var arr = [];
                        var item = {};
                        for (var j = 0; j < genList[i].tableColumns.length; j++) {
                            item[genList[i].tableColumns[j].model] = genList[i].tableColumns[j].options.defaultValue;
                        }
                        arr.push(item);
                        this.models[genList[i].model] = arr;
                    } else if (genList[i].type == 'card') {
                        this.models[genList[i].model] = [];
                        var arr = [];
                        var item = {};
                        for (var j = 0; j < genList[i].tableColumns.length; j++) {
                            item[genList[i].tableColumns[j].model] = genList[i].tableColumns[j].options.defaultValue;
                        }
                        arr.push(item);
                        this.models[genList[i].model] = arr;
                    } else if (genList[i].type == 'tabs') {
                        this.models[genList[i].model] = [];
                        var arr = [];

                        for (var j = 0; j < genList[i].tabColumns.length; j++) {
                            var innerNode = genList[i].tabColumns[j];
                            var innerArry = []
                            var item = {};
                            for (var k = 0; k < innerNode.length; k++) {

                                item[innerNode[k].model] = innerNode[k].options.defaultValue;
                            }
                            arr.push(item)
                            // genList[i].tableColumns[j].options.defaultValue;
                        }
                        this.models[genList[i].model] = arr;
                    } else if (genList[i].type == 'tabs' || genList[i].type == 'collapse') {
                        this.models[genList[i].model] = [];
                        var arr = [];

                        for (var j = 0; j < genList[i].tabColumns.length; j++) {
                            var innerNode = genList[i].tabColumns[j];
                            var innerArry = []
                            var item = {};
                            for (var k = 0; k < innerNode.length; k++) {

                                item[innerNode[k].model] = innerNode[k].options.defaultValue;
                            }
                            arr.push(item)
                            // genList[i].tableColumns[j].options.defaultValue;
                        }
                        this.models[genList[i].model] = arr;
                    } else {
                      if(genList[i].options.defaultValue){
                        if (genList[i].options.defaultValue.indexOf("${") != -1 ){
                          var keys=[];
                          var t=genList[i].options.defaultValue;
                          var arr = t.match(/\$\{(.*?)\}/g);
                          for(var key in arr){
                            var s=arr[key].replace("${","").replace("}","");
                            keys.push(s);
                          }
                          for(var j=0;j<keys.length;j++){
                            var key=keys[j];
                            var value=this.builtMap[key];
                            if (value){
                              t= t.replace("${"+key+"}",value);

                            }
                          }
                          this.models[genList[i].model]=t

                        }else{
                          this.models[genList[i].model] = genList[i].type == 'table' ? [] : genList[i].options.defaultValue

                        }

                      }else{
                        this.models[genList[i].model] = genList[i].type == 'table' ? [] : genList[i].options.defaultValue

                      }
                    }
                }
            },
            getData() {
                return new Promise((resolve, reject) => {
                    this.$refs.generateForm.validate(valid => {
                        if (valid) {
                            var models1 = this.models;
                            if (this.models_temp) {
                                for (var j = 0; j < this.models_temp.length; j++) {
                                    var key = this.models_temp[j];
                                    delete models1[key];
                                }
                            }
                            resolve(models1)
                        } else {
                            reject(new Error('表单数据校验失败').message)
                        }
                    })
                })
            },
            reset() {
                this.$refs.generateForm.resetFields()
            },
            refresh() {

            }
        },
        watch: {
            value: {
                deep: true,
                handler(val) {
                    this.models = {...this.models, ...val}
                }
            },
        }
    }
</script>

<style lang="scss">
    // @import '../styles/cover.scss';
    h3 {
        padding: 0px 32px;
    }
</style>
